package recycle.service;

import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import recycle.pojo.User;
import recycle.repository.UserRepository;
import recycle.utils.AesUtils;

public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Future<Long> create(User user) {
        return userRepository.insert(user);
    }

    public Future<JsonObject> list(User user , Integer pageNum, Integer pageSize) {
        return userRepository.selectList( user , pageNum, pageSize);
    }

    public Future<User> details(Long id) {
        return userRepository.selectById(id);
    }

    public Future<Void> update(User user) {
        return userRepository.updateById(user);
    }

    public Future<Void> delete(Long id) {
        return userRepository.deleteById(id);
    }

    public Future<String> login(User user) {
        return userRepository.selectByPhoneAndPassword(user.getPhone(), user.getPassword())
                .compose(foundUser -> {
                    if (foundUser != null) {
                        return Future.succeededFuture(AesUtils.encrypt(String.valueOf(foundUser.getId())));
                    } else {
                        return Future.failedFuture("手机号或密码错误");
                    }
                });
    }

    public Future<Boolean> exist(String phone) {
        return userRepository.selectByPhone(phone)
                .compose(foundUser -> Future.succeededFuture(foundUser != null));
    }

    public Future<User> detailsByUsername(String phone) {
        return userRepository.selectByPhone(phone);
    }
}